import { Component, OnInit } from "@angular/core";
import { Iwe7FormBuilderService } from "../iwe7-form-builder.service";
import { ActivatedRoute, Router } from "@angular/router";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: "create-table",
  templateUrl: "./create-table.component.html",
  styleUrls: ["./create-table.component.scss"]
})
export class CreateTableComponent implements OnInit {
  id: any = 0;
  fields: any[] = [];
  form: FormGroup;
  constructor(
    public fb: Iwe7FormBuilderService,
    public route: ActivatedRoute,
    public fb2: FormBuilder,
    public router: Router
  ) {
    this.route.queryParams.subscribe(res => {
      this.id = res.id || 0;
      this.getDetail(this.id);
    });
    this.form = this.fb2.group({});
  }

  ngOnInit() {}

  getDetail(id: any) {
    this.fb.getDetail(id).subscribe((res: any) => {
      this.fields = res.fields;
      //
      this.fields.map(item => {
        if (!this.form.contains(item.name)) {
          if (item.required) {
            this.form.addControl(
              item.name,
              this.fb2.control("", [Validators.required], [])
            );
          }
        }
      });
    });
  }

  saveData() {
    this.fb.saveData(this.id, this.form.value).subscribe(res => {
      this.router.navigate(["formBuilder/dataList"], {
        queryParams: {
          id: this.id || 0
        }
      });
    });
  }
}
